#pragma once
#include"Socket.hpp"
#include<functional>
typedef std::function<std::string( std::string&)> callback_;
class TcpServer
{
    public:
    TcpServer(const uint16_t& port,callback_ cb)
    :port_(port),cb_(cb)
    {

    }
  
    bool Init()
    {
        listenfd_.Socket();//1.创建套接字
        listenfd_.Bind(port_);//2.绑定套接字
        listenfd_.Linsten();//3.监听，让服务器处于一种等待被连接的状态
        return true;
    }
    void Start()
    {
        //为什么要忽略信号 PIPE? CHLD? SIG_IGN?
        while(true)
        {
            uint16_t peerport;
            std::string peerip;
          int sock_fd=listenfd_.Accept(&peerport,&peerip);//4.建立新链接
          if(sock_fd<0)
          {
            continue;
          }
          std::string inbuffer_stream;
          pid_t  pid=fork();
          if(pid==0)
          {
            listenfd_.Close();
            //提供服务
            while(true)
            {
            char buffer[1024];
            ssize_t n=read(sock_fd,buffer,sizeof(buffer));
            if(n>0)
            {
                buffer[n]='\0';
                inbuffer_stream+=buffer;
                std::string info=cb_(inbuffer_stream);
                if(info.empty())continue;//如果没得到有效的报文就继续读取
                write(sock_fd,info.c_str(),info.size());
            }
            else if(n==0)
            {
              break;
            }
            else break;
            }
          }

        close(sock_fd);
        }
    }
    ~TcpServer()
    {

    }
    private:
    uint16_t port_;
    Sock listenfd_;
    callback_ cb_;
};